package com.shan.domm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.shan.domm.common.ErrorCode;
import com.shan.domm.exception.BusinessException;
import com.shan.domm.mapper.UserMapper;
import com.shan.domm.model.domain.DTOs.UserRegister;
import com.shan.domm.model.domain.User;
import com.shan.domm.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.shan.domm.contant.UserConstant.USER_LOGIN_STATE;
/**
* @author 23949
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2024-03-27 20:31:45
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private UserMapper userMapper;

    public static final String SALT="shan";

    @Override
    public long userRegister(UserRegister userRegister) {
        String userAccount=userRegister.getUserAccount();
        String userPassword=userRegister.getUserPassword();
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码为空");
        }
        if(userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不能少于4位");
        }
        if(userPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不能少于8位");
        }
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不能包含特殊字符");
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",userAccount);
        long count=userMapper.selectCount(queryWrapper);
        if(count>0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已存在");
        }
        //2.加密密码
        String encryptPassword= DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
        //3.插入数据库
        User user=new User();
        user.setAccount(userAccount);
        user.setPassword(encryptPassword);
        user.setName(userRegister.getUserName());
        user.setIphone(userRegister.getUserIphone());
        user.setSex(userRegister.getUserSex());
        user.setRole(userRegister.getUserRole());
        user.setAvatarurl(userRegister.getAvatarUrl());
        boolean saveResult=this.save(user);
        if(!saveResult){
            return -1;
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword,HttpServletRequest request) {
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if(userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if(userPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher=Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数包含特殊字符");
        }
        //2.加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //查询用户存在
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",userAccount);
        queryWrapper.eq("password",encryptPassword);
        User user=userMapper.selectOne(queryWrapper);
        if(user==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        //3.用户脱敏
        User safetyUser=getSafetyUser(user);
        // 4.记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,user);
        Object userObj=request.getSession().getAttribute(USER_LOGIN_STATE);
        return safetyUser;

    }

    @Override
    public Boolean userLogout(HttpServletRequest request) {
        if(request.getSession().getAttribute(USER_LOGIN_STATE)==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"未登录");
        }
        //移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        Object userObj=request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser=(User) userObj;
        if(currentUser==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"未登录");
        }
        long userId=currentUser.getId();
        currentUser=this.getById(userId);
        if(currentUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        User safetyUser=getSafetyUser(currentUser);
        return safetyUser;
    }

    /**
     * 增加用户
     * @param user
     * @return
     */

    @Override
    public long addUser(User user) {
        String userAccount=user.getAccount();
        validUser(user);
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("account",userAccount);
        User userExist=userMapper.selectOne(queryWrapper);
        if(userExist!=null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户已存在");
        }
        String password=user.getPassword();
        String encryptPassword= DigestUtils.md5DigestAsHex((SALT+password).getBytes());
        user.setPassword(encryptPassword);
        int insert = userMapper.insert(user);
        if(insert<1) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"新增失败");
        }
        return user.getId();

    }

    @Override
    public long deleteUserById(Integer id) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        Long userExist=userMapper.selectCount(queryWrapper);
        if(userExist<1){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        int i = userMapper.deleteById(id);
        if(i<0){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
        return id;
    }

    @Override
    public long updateUser(User user) {
        String userAccount=user.getAccount();
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",user.getId());
        User userExist=userMapper.selectOne(queryWrapper);
        if(userExist==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        String password=user.getPassword();
        String encryptPassword= DigestUtils.md5DigestAsHex((SALT+password).getBytes());
        user.setPassword(encryptPassword);
        int i = userMapper.update(user, queryWrapper);
        if(i<0){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新失败");
        }
        return user.getId();
    }

    @Override
    public List<User> seacherUser(String name) {
        if(name==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("name",name);
        List<User> users = userMapper.selectList(queryWrapper);
        List<User> userList=new ArrayList<>();
        for(User user:users){
            userList.add(getSafetyUser(user));
        }
        return users;
    }

    public void validUser(User validUser){
        String userAccount=validUser.getAccount();
        String userPassword=validUser.getPassword();
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码为空");
        }
        if(userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不能少于4位");
        }
        if(userPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不能少于8位");
        }
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不能包含特殊字符");
        }
    }

    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setName(originUser.getName());
        safetyUser.setAccount(originUser.getAccount());
        safetyUser.setAvatarurl(originUser.getAvatarurl());
        safetyUser.setSex(originUser.getSex());
        safetyUser.setIphone(originUser.getIphone());
        safetyUser.setRole(originUser.getRole());
        safetyUser.setCreateTime(originUser.getCreateTime());
        return safetyUser;
    }
}




